# Create your views here.
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from bloganalisys.gui.forms import * #import all forms from this aplication
from urllib import urlopen
from bloganalisys.crawler import *
from bloganalisys.crawler.BlogParsers import *
from couchdb import Server
from couchdb.client import ResourceNotFound
import time
import cdb
SERVER = Server('http://127.0.0.1:5984')
# Narazie do testoww moze tak zostaca

db = SERVER[cdb.COUCH_DB]
content_fun = """def fun(doc):
    if doc['type'] == 'blog_note' and doc['context']:
      yield doc['_id'], doc"""

comment_fun = """def fun(doc):
    if doc['type'] == 'comment':
      yield doc['_id'], doc"""

get_blogs = """def fun(doc):
		if doc['type'] == 'blog':
			yield doc['_id'], doc"""

def try_again(f):
	def opakowanie(*args, **kwds):
		try:
			return f(*args, **kwds)
		except ResourceNotFound:
			print 'nieznaleziono elementu'
			return []
		except:
			print "zlapalem wyjatek"
			return f(*args, **kwds)
	return opakowanie

@try_again
def get(id):
  return db[id]

@try_again
def zapytanie(fun):
  return db.query(fun, language="python") 



if (len(SERVER) == 0):
    SERVER.create('docs')
	
if not 'temp' in SERVER:
	SERVER.create('temp')

class URLError(Exception):
	pass

def browser_blog(request):

	ret = {}
	blogs = zapytanie(get_blogs)
	lista = []
	for res in blogs:
		temp = res['value']
		lista.append( (temp['_id'],  temp['author'], temp['blog_name']) )
		

	ret = { 'type' : 'blog_list',	'blog_list' : lista }

	#zwraca lista blogow znajdujacych sie w bazie.
	return 	render_to_response("browser_start.html", ret )


komentarze = """function(doc) {
if (doc["type"] == "comment" && doc["base_address"] == "%s" ) {
  emit(null, doc);
}
}"""

def browser_comments(request, id):

	ret = { 'type' : 'comment_list'}
	x = db[id]
	address = x['address']
	lista = []
	topic = x['topic']
	name = x['name']
	author = x['author']

	for komentarz in db.query(komentarze % address ):
		temp = komentarz['value']
		lista.append( ( temp['_id'], temp['topic'], temp['date'], temp['author']   ) )

	ret['name'] = name
	ret['author'] = author 
	ret['topic'] = topic
	ret['comment_list'] = lista
	return 	render_to_response("browser_start.html", ret )





wpisy = """function(doc) {
if (doc["type"] == "blog_note" && doc["name"] == "%s" ) {
  emit(null, doc);
}
}"""


def browser_note(request, id):

	ret = { 'type' : 'note_list'}
	nazwa = db[id]['blog_name']
	lista = []
	author = db[id]['author']
	for wpis in db.query(wpisy % nazwa ):
		temp = wpis['value']
		lista.append( ( temp['_id'], temp['topic'], temp['date']   ) )

	ret['name'] = nazwa
	ret['author'] = author 
	ret['note_list'] = lista
	return 	render_to_response("browser_start.html", ret )

def browser_info(request, id=None):
	
	db = SERVER[cdb.COUCH_DB]
	try:
		temp = db[id]
	except:
		temp = db[id]

	typ = temp['type']
	if typ == 'blog_note':
		
		add_time = temp['add_time']
		author = temp['author']
		blog_name = temp['name']
		content = temp['context']
		address = temp['address']
		base_address = temp['base_address']
		date = temp['date']
		blog_name = temp['name']
		topic = temp['topic']

		ret = {'add_time' : add_time, 
		'author' : author, 
		'blog_name' :blog_name, 
		'content' :content,
		'type' : 'blog_note',
		'address' : address, 
		'base_address' : base_address, 
		'date_' : date, 
		'topic' : topic,
		'id_' : id}

		print ret

	elif typ == 'comment':
		add_time = temp['add_time']
		content = temp['content']
		blog_name = temp['blog_name']
		author = temp['author']
		date = temp['date']
		address = 'http://' + blog_name + temp['portal'] + "/" + temp['address']

		ret = {'id_' : id, 'add_time' : add_time, 'date_' : date , 'content' : content, 'blog_name' : blog_name, 'author' : author , 'type' : 'comment', 'address' : address} 
	elif typ == 'blog':
		author = temp['author']
		blog_name = temp['blog_name']
		add_time = temp['add_time']
		address = 'http://'+blog_name+temp['portal']

		ret = { 'id_' : id, 'add_time' : add_time, 'author' : author, 'blog_name' : blog_name, 'type' : 'blog', 'address' : address }



	else:
		ret = { 'type' : 'UNKNOWN' }

	return render_to_response('browser_info.html', ret )
	print id
	info =  [(id,id, temp['context'], temp['address']) ]
	print info
	
	"""
  if temp['type'] == 'blog_list':
		list = temp['ids']
		
		for i in list:
	  	try:
				record = db[i]
				
				#zavezpieczyc przed nieporawnymi danymi
				address = record['address']
				topic = record['topic']
				date = record['date']
				info_list.append( [i, address, topic, date ])
				#print info_list
			except KeyError:
			    pass

	if temp['type'] == 'blog_content':
	    content = temp['content']
	    address = temp['address']
	    info_list.append([id, content, address ])
	
	if temp['type'] == 'comment_list':
		
		list = temp['ids']
		
		for i in list:
			try:
				record = db[i]
				
				#zavezpieczyc przed nieporawnymi danymi
				
				
				address = record['address']
				topic = record['topic']
				c_id = record['c_id']
				#date = record['date']
				info_list.append( [i, c_id,  address, topic ])
				
				#print info_list
			except KeyError:
				print 'blod'
			    
	
	print len(info_list)
	info = info_list
	"""
	return render_to_response('crawler_info.html', {"co" : "browser", "info": info, 'type' : 'blog_content'})

